﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.UI;
using System.Web.UI.WebControls;
using Marbles.Core.Content.Pages;
using Marbles.Core.Connectors;
using System.Data;
using Marbles.Core.Settings;
using Marbles.Core.Content.Templates;

namespace Marbles.Web.Admin.Content
{
    public partial class PageMgr : ContentBase
    {
        protected void Page_Load(object sender, EventArgs e)
        {
            if ((!Page.IsPostBack) || (cDrpManagingEditor.Items.Count == 0) || (cDrpParentPageId.Items.Count == 0))
            {
                InitialiseForm();
            }
            LoadData();
        }

        private void InitialiseForm()
        {
            DataConnection dbc = new DataConnection();
            Command cmd = new Command("SELECT DISTINCT a.username, a.fullname FROM Users a INNER JOIN usergrouplink b ON a.userid = b.userid INNER JOIN usergroups c ON b.groupid = c.groupid WHERE c.editor = 1 OR c.administrator = 1 AND a.siteid = @siteid ORDER BY fullname ASC");
            cmd.AddParameter("@siteid", CurrentWeb.SiteId);

            cDrpManagingEditor.Items.Clear();
            cDrpManagingEditor.Items.Add(new ListItem("", ""));
            foreach (DataRow dr in dbc.FetchDataTable(cmd).Rows)
            {
                cDrpManagingEditor.Items.Add(new ListItem(dr["fullname"].ToString(), dr["username"].ToString()));
            }

            TemplateCollection t = new TemplateCollection(CurrentWeb, false);
            cDrpTemplate.DataSource = t;
            cDrpTemplate.DataBind();
            cDrpTemplate.Items.Insert(0, new ListItem("", ""));
        }

        private void LoadParentPages(string currentpagename)
        {
            DataConnection dbc = new DataConnection();
            Command cmd = null;
            if (!string.IsNullOrEmpty(currentpagename))
            {
                cmd = new Command("SELECT pagename, title FROM Pages WHERE siteid = @siteid AND pagename <> @pagename ORDER BY title ASC");
                cmd.AddParameter("@siteid", CurrentWeb.SiteId);
                cmd.AddParameter("@pagename", currentpagename);
            }
            else
            {
                cmd = new Command("SELECT pagename, title FROM Pages WHERE siteid = @siteid ORDER BY title ASC");
                cmd.AddParameter("@siteid", CurrentWeb.SiteId);
            }
            cDrpParentPageId.Items.Clear();
            cDrpParentPageId.Items.Add(new ListItem("", ""));
            foreach (DataRow dr in dbc.FetchDataTable(cmd).Rows)
            {
                cDrpParentPageId.Items.Add(new ListItem(dr["title"].ToString(), dr["pagename"].ToString()));
            }
        }

        private void LoadData()
        {
            Core.Content.SiteMap.WebSiteMap map = new Core.Content.SiteMap.WebSiteMap(this.CurrentWeb, false);
            map.GetTreeNodes(cTreeContent.Nodes,true);
            cTreeContent.DataBind();
        }

        protected void cTreeContent_SelectedNodeChanged(object sender, EventArgs e)
        {
            PageDefinition def = new PageDefinition(this.CurrentWeb.SiteName, cTreeContent.SelectedNode.Value);
            LoadParentPages(def.PageName);
            cDrpParentPageId.SelectedValue = def.ParentPageName;
            cDrpManagingEditor.SelectedValue = def.ManagingEditor;
            cTxtDescription.Text = def.Description;
            cDrpTemplate.ClearSelection();
            foreach (ListItem item in cDrpTemplate.Items)
            {
                if (item.Value == def.TemplateName) { item.Selected = true; break; }
            }
            
            cTxtKeywords.Text = def.Keywords;
            cLblLastAccess.Text = def.LastAccessDate;
            cTxtPageName.Text = def.PageName;
            cTxtPageName_TextChanged(cTxtPageName, EventArgs.Empty);
            cTxtPubDate.Text = def.PublishDate.ToString("dd/MM/yyyy HH:mm:ss");
            cTxtTitle.Text = def.Title;
            cChkAllowComments.Checked = def.AllowComments;
            cChkAllowFeedDiscovery.Checked = def.AllowFeedDiscovery;
            cChkPublished.Checked = def.Published;
            cChkSyndicate.Checked = def.Syndicate;
            cChkTheme.Checked = def.ApplyTheme;
            cBtnSave.CommandArgument = def.PageName;
            cBtnSave.CommandName = "Save";
            cBtnNew.Enabled = false;
            cBtnSave.Enabled = true;
            cBtnCancel.Enabled = true;
            SetState(true);
            if (this.CurrentWeb.AllowComments) { cChkAllowComments.Enabled = true; }
            else
            {
                cChkAllowComments.Enabled = false;
                cChkAllowComments.Checked = false;
            }
        }

        private void SetState(bool enabled)
        {
            cChkTheme.Enabled = enabled;
            cChkPublished.Enabled = enabled;
            cDrpTemplate.Enabled = enabled;
            cDrpManagingEditor.Enabled = enabled;
            cDrpParentPageId.Enabled = enabled;
            cTxtDescription.Enabled = enabled;
            cTxtKeywords.Enabled = enabled;
            cTxtPageName.Enabled = enabled;
            cTxtPubDate.Enabled = enabled;
            cTxtTitle.Enabled = enabled;
            cChkAllowFeedDiscovery.Enabled = enabled;
            cChkSyndicate.Enabled = enabled;
            cChkAllowComments.Enabled = enabled;
            if (enabled)
            {
                cChkAllowComments.Enabled = this.CurrentWeb.AllowComments;
                if (!this.CurrentWeb.AllowComments) { cChkAllowComments.Checked = false; }
            }
        }

        private void Clear()
        {
            cDrpParentPageId.ClearSelection();
            cDrpManagingEditor.ClearSelection();
            cDrpManagingEditor.ClearSelection();
            cDrpTemplate.ClearSelection();
            cTxtDescription.Text = "";
            cTxtKeywords.Text = "";
            cTxtPageName.Text = "";
            cLblLink.Text = "";
            cChkPublished.Checked = false;
            cTxtPubDate.Text = "";
            cTxtTitle.Text = "";
            cChkTheme.Checked = false;
            cChkAllowFeedDiscovery.Checked = false;
            cChkAllowComments.Checked = false;
            cChkSyndicate.Checked = false;
            cBtnSave.CommandArgument = "";
            cBtnSave.CommandName = "Insert";
            cBtnSave.Enabled = false;
            cBtnCancel.Enabled = false;
            cBtnNew.Enabled = true;
            cTxtPubDate.Text = DateTime.Now.ToString("dd/MM/yyyy HH:mm:ss");
            SetState(false);
        }

        protected void Page_Command(object sender, CommandEventArgs e)
        {
            PageDefinition def = null;

            switch (e.CommandName)
            {
                case "New":
                    Clear();
                    cBtnSave.Enabled = true;
                    cBtnCancel.Enabled = true;
                    cBtnNew.Enabled = false;
                    SetState(true);
                    LoadParentPages("");
                    break;
                case "Save":
                    def = new PageDefinition(CurrentWeb.SiteName, e.CommandArgument.ToString());
                    def.ParentPageName = cDrpParentPageId.SelectedValue;
                    def.ManagingEditor = cDrpManagingEditor.SelectedValue;
                    def.PageName = cTxtPageName.Text.Trim();
                    def.Title = cTxtTitle.Text.Trim();
                    def.PublishDate = DateTime.Now;
                    def.Keywords = cTxtKeywords.Text.Trim();
                    def.Description = cTxtDescription.Text.Trim();
                    def.Syndicate = cChkSyndicate.Checked;
                    def.AllowFeedDiscovery = cChkAllowFeedDiscovery.Checked;
                    def.AllowComments = cChkAllowComments.Checked;
                    def.TemplateName = cDrpTemplate.SelectedValue;
                    def.ApplyTheme = cChkTheme.Checked;

                    if ((!def.Published) && (cChkPublished.Checked)) { def.Publish(); }

                    def.Published = cChkPublished.Checked;
                    def.Update(this.Page.Username);
                    Clear();
                    cBtnCancel.Enabled = false;
                    cBtnSave.Enabled = false;
                    LoadData();
                    break;
                case "Insert":
                    def = PageDefinition.CreateNew(CurrentWeb.SiteName);
                    def.ParentPageName = cDrpParentPageId.SelectedValue;
                    def.ManagingEditor = cDrpManagingEditor.SelectedValue;
                    def.PageName = cTxtPageName.Text.Trim();
                    def.Title = cTxtTitle.Text.Trim();
                    def.PublishDate = DateTime.Now;
                    def.Keywords = cTxtKeywords.Text.Trim();
                    def.AllowComments = cChkAllowComments.Checked;
                    def.Description = cTxtDescription.Text.Trim();
                    def.TemplateName = cDrpTemplate.SelectedValue;
                    def.Syndicate = cChkSyndicate.Checked;
                    def.AllowFeedDiscovery = cChkAllowFeedDiscovery.Checked;
                    def.ApplyTheme = cChkTheme.Checked;

                    if (cChkPublished.Checked) { def.Publish(); }
                    def.Published = cChkPublished.Checked;
                    def.Insert(this.Page.Username);
                    Clear();
                    cBtnCancel.Enabled = false;
                    cBtnSave.Enabled = false;
                    LoadData();
                    break;
                case "Cancel":
                    Clear();
                    cBtnCancel.Enabled = false;
                    cBtnSave.Enabled = false;
                    break;
            }
        }

        protected void cTxtPageName_TextChanged(object sender, EventArgs e)
        {
            if (SettingsManager.TrustLevel == AspNetHostingPermissionLevel.Medium)
            {
                cLblLink.Text = "/?id=" + cTxtPageName.Text;
            }
            else
            {
                cLblLink.Text = cTxtPageName.Text + ".aspx";
            }
        }
    }
}